var daoFactory = require('../dao'),
	Article = daoFactory.get('article');
	async = require('async');

exports.mappings = mappings = [];

mappings.push({method : 'get' ,url:'article' , handler: get});
function get(req ,res){
	
	var _start = (parseInt(req.query.start) - 1) * req.query.limit,
        _limit = req.query.limit,
        filter = req.query.filter;

    var query = Article.find();
    if(filter && filter != 'all'){
		var cond = {};
		cond['meta.' + filter] = true;
        query.and([{'hidden' :false} ,cond]);
    }else{
		query.gte('hidden' ,false);
	}
	query.sort({ 'pub_date': 'asc'});
	var task1 = function(callback){
        query.skip(_start)
            .limit(_limit)
			.slaveOk()
			.exec(function(err ,data){
				callback(err ,data);
			});
	}
	var task2 = function(callback){
        query.count()
            .exec(function(err ,count){
				if(err){
				}
                //console.log(count);
				callback(err ,count);
			});
	}
	// TODO: 当参数为空时 会获取全部数据
	async.series([task1,task2],function(err ,results){
		res.send({
			start : _start,
			limit : _limit,
			total : results[1],
			page : results[0]
		});
	});







    // 添加测试数据
    var article = new Article({
        title : req.query.title + Math.random().toFixed(3)*1000
    });
    article.save(function(){
        Article.findOne(article ,function(err, doc){
            //console.log(1,doc);
        })
    });
    //===================================================================
}

mappings.push({method : 'delete' ,url:'article' ,handler : remove});
function remove(req ,res){

    Article.remove({_id : req.query._id} ,function(data){
		var result = {success : true};
		res.send(result);
	});
}